package com.example.demo2.controller;

import com.example.demo2.controller.requests.ModifyDrinkRequest;
import com.example.demo2.model.Drink;
import lombok.extern.slf4j.Slf4j;
import org.joda.money.CurrencyUnit;
import org.joda.money.Money;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.validation.Valid;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/drink")
public class DrinkController {
    //get  drink
    @GetMapping("/")
    public List<Drink> getAll() {
        //mock数据
        List<Drink> result = new ArrayList<>();
        result.add(Drink.builder().id(1).name("可乐").price(Money.parse("USD 3")).build());
        result.add(Drink.builder().id(2).name("雪碧").price(Money.parse("USD 3")).build());
        result.add(Drink.builder().id(3).name("鲜橙多").price(Money.parse("USD 3")).build());
        result.add(Drink.builder().id(4).name("冰红茶").price(Money.parse("USD 3")).build());
        return result;
    }

    @GetMapping("/{id}")
    public Drink getDrink(@PathVariable Integer id) {
        log.info("商品的id：{}", id);
        Drink drink = Drink.builder().id(1).name("可乐").price(Money.parse("USD 3")).build();
        return drink;
    }

    //新增
    @PostMapping("/")
    public Drink AddNewDrink(@RequestBody @Valid Drink drink, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            for (ObjectError error : bindingResult.getAllErrors()) {
                log.error(error.toString());
            }
            return null;
        } else {

            log.info("创建新饮品：{}", drink);
            Drink AddDrink = Drink.builder().id(1).name("可乐").
                    price(Money.parse("USD 3")).build();
            return AddDrink;
        }
    }

    //修改饮品
    @PutMapping("/")
    public Drink modIfyDrink(@RequestBody ModifyDrinkRequest request){
        log.info("要修改的饮品：{}",request);
        Drink AddDrink = Drink.builder().id(1).name("可乐").
                price(Money.parse("USD 3")).build();
        return AddDrink;
    }
    @DeleteMapping("/{id}")
    public String  deleteDrink(@PathVariable Integer id){
        log.info("要删除的饮品id:{}",id);
        return "删除成功";
    }

    /**
     * 文件上传
     * 前端必须使用html form
     * 前端类型必须设置为 multipart/form-data
     */
    @PostMapping(value = "/upload",consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
     public String uploadFile(MultipartFile file){
        String dest="E:\\upload";
        String destFileName=dest + file.getOriginalFilename();
//        File destFile=new File(destFileName);
//        file.transferTo(destFile);
        return "上传成功";
     }

    /**
     * 批量创建饮品
     *
     */
    @PostMapping(value = "/batch", consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
    public List<Drink> batchAddNewDrink(MultipartFile file) {
        List<Drink> results = new ArrayList<>();
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(file.getInputStream()));
            String line = "";
            while ((line = reader.readLine())!=null) {
                // 解析一行
                String[] args = line.split(",");
                Drink drink = Drink.builder()
                        .id(Integer.parseInt(args[0]))
                        .name(args[1])
                        .price(Money.of(CurrencyUnit.of("CNY"), Double.parseDouble(args[2])))
                        .build();
                results.add(drink);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return results;
    }
}